﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SerializeExtensions;

namespace ApplicationSupport
{
    public class Configuration<T> where T : IConfiguration, new()
    {
        // TODO these are only her incase we support option of binary later, it could be written without them
        private delegate object SerialiseInput(Type objToSerialise, string fileName);
        private delegate void SerialiseOutput(object objToSerialise, string fileName);

        private T m_configurationItem;
        public T ConfigurationItem
        {
            get { return m_configurationItem; }
            set { m_configurationItem = value; }
        }

        private string m_file = typeof(T).ToString() + ".xml";

        SerialiseInput m_serialInput;
        SerialiseOutput m_serialOutput;

        /// <summary>
        /// 
        /// </summary>
        public Configuration()
        {
            //TODO should we refactor this to be the class type
            m_serialInput = Serialize.FromXMLFile;
            m_serialOutput = Serialize.ToXMLFile;

            m_configurationItem = new T();
        }

        public void SetFile(string fileName)
        {
            m_file = fileName;
        }

        public bool Load()
        {
            string fileName = PathManager.Instance.ApplicationFolder + @"\" + m_file;
            bool configurationLoaded = false;

            if (File.Exists(fileName))
            {
                try
                {
                    m_configurationItem = (T)m_serialInput(typeof(T), fileName);
                    configurationLoaded = true;
                    if (m_configurationItem == null)
                    {
                        m_configurationItem = new T();
                        m_configurationItem.DefaultConfiguration();
                    }
                    else
                    {
                        m_configurationItem.CheckConfiguration();
                    }
                }
                catch
                {
                    m_configurationItem = new T();
                    m_configurationItem.DefaultConfiguration();
                }
            }

            return configurationLoaded;
        }

        public void LoadDefault()
        {
            if (m_configurationItem == null)
            {
                m_configurationItem = new T();
            }
            m_configurationItem.DefaultConfiguration();
        }

        public void Save()
        {
            string fileName = PathManager.Instance.ApplicationFolder + @"\" + m_file;
            m_serialOutput(m_configurationItem, fileName);
        }
    }
}
